package com.per.shardingbeetlsqldemo.service;

import cn.hutool.core.collection.CollUtil;
import com.per.shardingbeetlsqldemo.dao.OrderDao;
import com.per.shardingbeetlsqldemo.entity.Order;
import com.per.shardingbeetlsqldemo.util.CreateTableUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: Cheng
 * @date: 2019/12/9 22:04
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Slf4j
public class OrderService {
    private final OrderDao orderDao;

    private final CreateTableUtil createTableUtil;

    public void addOrder(Integer userId, String name) {
        String tableName = "`order" + userId + "`";
        String sql = "create table IF NOT EXISTS " + tableName + " (\n" +
                "  `order_id` bigint(20) NOT NULL AUTO_INCREMENT,\n" +
                "  `user_id` bigint(20) NOT NULL,\n" +
                "  `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  PRIMARY KEY (`order_id`) USING BTREE\n" +
                ") ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;";
        try {
            createTableUtil.createTable(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Order order = Order.builder()
                .userId(userId)
                .name(name)
                .build();
        orderDao.insertTemplate(order);
    }

    public Order getOrder(Integer orderId, Integer userId) {
        return orderDao.createLambdaQuery()
                .andEq(Order::getOrderId, orderId)
                .andEq(Order::getUserId, userId)
                .single();
    }

    public List<Order> getAll() {
        List<Integer> list = CollUtil.newArrayList();
        list.add(0);
        list.add(1);
        return orderDao.createLambdaQuery()
                .andIn(Order::getUserId, list)
                .select();
    }
}
